//引入axios
import axios from 'axios'
import {Loading,MessageBox} from 'element-ui';
let cancel, promiseArr = {};
let loading = '';
const CancelToken = axios.CancelToken;
//请求拦截器
axios.interceptors.request.use(config => {
	//发起请求时，取消掉当前正在进行的相同请求
	if (promiseArr[config.url]) {
		promiseArr[config.url]('操作取消')
		promiseArr[config.url] = cancel
	} else {
		promiseArr[config.url] = cancel
	}
	return config
}, error => {
	return Promise.reject(error)
})

//响应拦截器即异常处理
axios.interceptors.response.use(response => {
	// loading.close();
	switch (response.status) {
		case 200:
			if (Object.prototype.toString.call(response.data) != '[object Object]') {
				response.data = JSON.parse(response.data)
			}
			if (response.data.code == 200) {
				return Promise.resolve(response.data)
			} else {
				// MessageBox.confirm(response.data.msg, '提示', {
				// 	confirmButtonText: '确定',
				// 	 cancelButtonText: '取消',
				// 	type: 'error'
				// });
				return Promise.resolve(response.data)
			}
			break;
		default:
			// MessageBox.confirm('请求错误，请检查网络（' + response.statusText + '）', '提示', {
			// 	confirmButtonText: '确定',
			// 	 cancelButtonText: '取消',
			// 	type: 'error'
			// });
			return Promise.resolve(response.data)
	}
});

//设置接口前面拼接的目录
axios.defaults.baseURL = '';
//设置请求头
axios.defaults.headers = {
	'X-Requested-With': 'XMLHttpRequest_3b4604bb=b855d124-aab9-441a-8c3e-5cdd941c3a1a'
}
axios.defaults.timeout = 10000;

export default {
	//get请求
	get(url, param) {
		param.t = Date.parse(new Date());//加上时间戳，以防止==》浏览器缓存造成axios不请求接口
		// loading = Loading.service({
		// 	lock: true,
		// 	text: '数据加载中，请稍后...',
		// 	spinner: 'el-icon-loading',
		// 	background: 'rgba(0, 0, 0, 0.5)'
		// });
		return new Promise((resolve, reject) => {
			axios({
				method: 'get',
				url,
				params: param,
				cancelToken: new CancelToken(c => {
					cancel = c
				})
			}).then(res => {
				if (Object.prototype.toString.call(res) != '[object Object]') {
					res = JSON.parse(res)
				}
				// loading.close();
				resolve(res)
			})
		})
	},
	//post请求
	post(url, param) {
		param.t = Date.parse(new Date());//加上时间戳，以防止==》浏览器缓存造成axios不请求接口
		// loading = Loading.service({
		// 	lock: true,
		// 	text: '数据加载中，请稍后...',
		// 	spinner: 'el-icon-loading',
		// 	background: 'rgba(0, 0, 0, 0.5)'
		// });
		return new Promise((resolve, reject) => {
			axios({
				method: 'post',
				url,
				data: param,
				cancelToken: new CancelToken(c => {
					cancel = c
				})
			}).then(res => {
				if (Object.prototype.toString.call(res) != '[object Object]') {
					res = JSON.parse(res)
				}
				// loading.close();
				resolve(res)
			})
		})
	}
}
